package cn.itcast.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/exportServlet")
public class ExportServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //解决乱码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //
        response.setHeader("content-type",super.getServletContext().getMimeType(".txt"));
        response.setHeader("content-disposition","attachement;filename=stu.txt");

        FileInputStream fis = new FileInputStream("D:/stu.txt");
        ServletOutputStream os = response.getOutputStream();

        byte[] arr = new byte[1024];
        int len;
        while ((len = fis.read(arr))!= -1){
            os.write(arr,0,len);
        }
        fis.close();


    }
}
